/**
 * Copyright (C) 2010 D. Zoller, M. Richter, M. Blumenstein & W. Biller
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.siafu.rest.commands.parser;

import static com.googlecode.siafu.rest.commands.parser.util.SiafuResultParserHelper.KEY_VALUE_REGEX;
import static com.googlecode.siafu.rest.commands.parser.util.SiafuResultParserHelper.getBooleanValue;
import static com.googlecode.siafu.rest.commands.parser.util.SiafuResultParserHelper.getValue;
import static com.googlecode.siafu.rest.commands.parser.util.SiafuResultParserHelper.parsePosition;

import com.googlecode.siafu.rest.commands.AbstractSiafuTCPCommand;
import com.googlecode.siafu.rest.exceptions.ResourceNotFoundException;
import com.googlecode.siafu.rest.model.Agent;
import com.googlecode.siafu.rest.model.Place;


/**
 * 
 * @author D. Zoller
 * @version $Id: AgentResultParser.java,v 1.6 2010-06-15 13:56:46 nosebrain Exp $
 */
public class AgentResultParser extends DefaultSiafuResultParser<Agent> {
	
	@Override
	public Agent parse(String string) {
		super.parse(string);
		
		if (string == null) {
			return null;
		}
		
		if (string.indexOf("ERR - Unknown context variable: \"atDestination\"") > -1) {
			throw new ResourceNotFoundException(); // a place with the name was found instead of an agent
		}
		
		final String[] parts = string.split(AbstractSiafuTCPCommand.RESPONSE_SPLITTER);
		
		final Agent agent = new Agent();
		
		if (parts.length > 0) {
			agent.setName(parts[0].split(KEY_VALUE_REGEX)[0]);
		}
		
		agent.setPosition(parsePosition(getValue(parts[0])));
		
		if (parts.length > 1) {
			agent.setAtDestination(getBooleanValue(parts[1]));
		}
		
		if (parts.length > 2) {
			final Place destination = new Place();
			
			final String[] infos = parts[2].split("#");
			destination.setName(infos[0].split(KEY_VALUE_REGEX)[1].split(":")[1]);
			destination.setType(infos[1]);
			destination.setPosition(parsePosition(infos[2] + "#" + infos[3]));
			
			agent.setDestination(destination);
		}
		
		return agent;
	}
	
}
